package datasource

import (
	"fmt"
	"iris-starter/config"
	"log"

	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

var (
	GDB *gorm.DB
)

func InitMysql(cfg *config.Config) error {
	return openDB(cfg)
}

func openDB(cfg *config.Config) error {
	mConf := cfg.MySQL
	dsn := fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8mb4&parseTime=True&loc=Local",
		mConf.UserName,
		mConf.Password,
		mConf.Addr,
		mConf.Name,
	)
	open, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		log.Fatalf("database open err:%v", err)
	}
	GDB = open
	return nil
}
